package com.coconet.gas.service.impl;

import com.coconet.gas.constant.dwEnum;
import com.coconet.gas.exception.ServiceException;
import com.gxa.entity.*;
import com.gxa.inter.OpenvasToolInter;
import com.gxa.util.OpenvasStatusException;
import opvas.SSHLinux;
import org.apache.commons.lang3.StringUtils;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.xml.sax.InputSource;
import org.apache.commons.exec.*;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class OpenvasTool2 implements OpenvasToolInter {

    @Value("${ssh.host}")
    private String host;
    @Value("${ssh.user}")
    private String user;
    @Value("${ssh.port}")
    private Integer port;
    @Value("${ssh.pwd}")
    private String pwd;

    private String route = "/usr/bin/";
    //openvas 新版本使用命令
    //private String command = "gvm-cli --gmp-username admin --gmp-password admin  socket --sockpath /var/run/gvm/gvmd.sock  --xml '";
    //private String command = "gvm-cli --gmp-username admin --gmp-password admin123  socket --sockpath /run/gvm/gvmd.sock --xml '";
    private String command = "gvm-cli --gmp-username admin --gmp-password contrail123  socket --sockpath /opt/gvm/run/gvm/gvmd.sock --xml '";
    // /opt/gvm/run/gvm/gvmd.sock


    private static String exec(String command) throws Exception {
        StringBuilder sb = new StringBuilder();
        StringBuilder sbErr = new StringBuilder();
        String[] cmdA = {"/bin/sh", "-c", command};
        //"/bin/sh", "-c",
        Process process;
        process = Runtime.getRuntime().exec(cmdA);
        InputStream fis = process.getInputStream();
        InputStream fisErr = process.getErrorStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(fis, "utf-8"));
        String line = null;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        BufferedReader brErr = new BufferedReader(new InputStreamReader(fisErr, "GB2312"));
        String lineErr = null;
        while ((lineErr = brErr.readLine()) != null) {
            sbErr.append(lineErr + "\n");
        }
        System.out.println(sbErr);
        return sb.toString();
    }

    public static String execCMD(String command) throws Exception {
        try (ByteArrayOutputStream out = new ByteArrayOutputStream();) {
            int exitCode = exeCommand(command, out);
            if (exitCode == 0) {
                System.out.println("命令运行成功！  " + command);
            } else {
                System.out.println("命令运行失败！  " + command);
            }
            return out.toString("UTF-8");
        }
    }

    private String execSshCMD(String command) throws Exception {
        String res = SSHLinux.exeCommand(host, port, user, pwd, command);
        return res;
    }

    //SAXBuilder获取Document对象
    private Document getDocument(String xmlstring) throws Exception {
        StringReader read = new StringReader(xmlstring);
        InputSource source = new InputSource(read);
        //analysis
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(source);
        return doc;
    }

    //判断状态码
    private void judgeStatus(Element root) throws Exception {
        String status = root.getAttributeValue("status");//返回的状态码：200成功 404not found
        String statusText = root.getAttributeValue("status_text");//返回的状态信息
        switch (status) {
            case "200":
            case "201":
            case "202":
                break;
            default:
                throw new OpenvasStatusException(statusText);
        }
    }
    @Override
    public List<Map<String, Object>>getPortList() throws Exception {
        //存储格式为：[{name:name,comment:comment,...},{},{},...]
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<get_port_lists details=\"1\" targets=\"1\" filter=\"sort=name first=1 rows=9999\"/>");
        //xmlcmd.append("<get_port_lists/>");
        //String xmlString = exec("omp -u admin -w admin --xml='" + xmlcmd + "'");

        String xmlString = exec(command + xmlcmd + "'");
        //String xmlString = execSshCMD("omp -u admin -w admin --xml='" + xmlcmd + "'");
        List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);//判断返回的状态码
        //获取portList子节点列表
        List<Element> portlist = root.getChildren("port_list");
        //遍历portList
        for (int i = 0; i < portlist.size(); i++) {
            Element e = portlist.get(i);
            Map<String, Object> mape = new HashMap<String, Object>();
            String portId = e.getAttributeValue("id");
            String name = e.getChildText("name");
            String allcount = e.getChild("port_count").getChildText("all");//端口总数
            String tcpcount = e.getChild("port_count").getChildText("tcp");//tcp端口数
            String udpcount = e.getChild("port_count").getChildText("udp");//udp端口数
            mape.put("portId", portId);
            mape.put("name", name);
            mape.put("allcount", allcount);
            mape.put("tcpcount", tcpcount);
            mape.put("udpcount", udpcount);
            resultList.add(mape);
        }
        return resultList;
    }

    @Override
    public Map<String, Object> getOnePortListRanges(String portlistId) throws Exception {
        //存储格式为：name：name,comment:comment,rangelist:[{},{},{}];
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<get_port_lists port_list_id='" + portlistId + "' details=\"1\" targets=\"1\"/>");
        //String xmlString = ( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        String xmlString = (command + xmlcmd + "'");
        Map<String, Object> resultmap = new HashMap<String, Object>();
        //try {

        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);//判断返回的状态码
        Element portele = root.getChild("port_list");
        String name = portele.getChildText("name");
        String comment = portele.getChildText("comment");
        Element portranges = portele.getChild("port_ranges");
        //获取port_ranges子节点列表
        List<Element> rangeslist = portranges.getChildren("port_range");
        //list存储port_ranges子节点数据
        List<Map<String, Object>> rangeList = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < rangeslist.size(); i++) {
            Element e = rangeslist.get(i);
            String rangeId = e.getAttributeValue("id");
            Map<String, Object> rmap = new HashMap<String, Object>();
            String type = e.getChildText("type");//range 类型：tcp/udp
            String start = e.getChildText("start");//range 起始端口
            String end = e.getChildText("end");//range 结束端口
            String rcomment = e.getChildText("comment");
            rmap.put("rangeid", rangeId);
            rmap.put("type", type);
            rmap.put("start", start);
            rmap.put("end", end);
            rmap.put("rcomment", rcomment);
            rangeList.add(rmap);
        }
        resultmap.put("name", name);
        resultmap.put("comment", comment);
        resultmap.put("rangeslist", rangeList);
		/*}catch(Exception e) {
			e.printStackTrace();
		}*/
        return resultmap;
    }
    @Override
    public void createPortRanges(String portId, String type, String start, String end) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<create_port_range>");
        xmlcmd.append("<port_list id='" + portId + "'>");
        xmlcmd.append("<start>" + start + "</start>");
        xmlcmd.append("<end>" + end + "</end>");
        xmlcmd.append("<type>" + type + "</type>");
        xmlcmd.append("</create_port_range>");
        //String xmlString = ( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        //新版本

        String xmlString = (command + xmlcmd + "'");
        //try {
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
		/*}catch(Exception e) {
		/	e.printStackTrace();
		}*/
    }

    @Override
    public void createPortList(String name, String comment, String port_range) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<create_port_list>");
        xmlcmd.append("<name>" + name + "</name>");
        xmlcmd.append("<comment>" + comment + "</comment>");
        xmlcmd.append("<port_range>" + port_range + "</port_range>");
        xmlcmd.append("</create_port_list>");

        //String xmlString = exec( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        String xmlString = exec(command + xmlcmd + "'");
        //String xmlString = execSshCMD( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        //try {
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
		/*} catch (Exception e) {
			e.printStackTrace();
		}*/
    }

    @Override
    public void deletePortRanges(String portrangeId) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<delete_port_range port_range_id='" + portrangeId + "'/>");

        //String xmlString = exec( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        String xmlString = exec("gvm-cli --gmp-username admin --gmp-password contrail123  socket --sockpath /var/run/gvm/gvmd.sock --xml \"" + xmlcmd + "\"");
        //String xmlString = execSshCMD( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        //try {
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
		/*} catch (Exception e) {
			e.printStackTrace();
			return false;
		}*/
    }

    @Override
    public void deletePortList(String portId) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<delete_port_list port_list_id='" + portId + "'/>");

        //String xmlString = exec( "omp -u admin -w admin --xml=\"" + xmlcmd + "\"");
        String xmlString = exec("gvm-cli --gmp-username admin --gmp-password contrail123  socket --sockpath /run/gvm/gvmd.sock --xml \"" + xmlcmd + "\"");
        //String xmlString = execSshCMD( "omp -u admin -w admin --xml=\"" + xmlcmd + "\"");
        //try {
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
		/*} catch (Exception e) {
			e.printStackTrace();
			return false;
		}*/
    }

    @Override
    public List<TargetEntity> getTargetList() throws Exception {
        //存储格式：[{name：name,comment:comment,credential:[{},{},{}]}，{}，{}，。。。]
        StringBuilder xmlcmd = new StringBuilder();
        List<TargetEntity> resultList = new ArrayList<TargetEntity>();
        xmlcmd.append("<get_targets filter=\"sort=name first=1 rows=9999\"/> ");
        //filter="sort=name first=1 rows=9999"
        String xmlString = null;
        //String[] cmdA = {"/bin/sh", "-c","su - gvm"};
        //xmlString = exec("whoami");
        //xmlString = exec( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        xmlString = exec(command + xmlcmd + "'" );
        //xmlString = execSshCMD( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        //omp -u admin -w admin --xml='<get_targets/>'
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
        List<Element> targetList = root.getChildren("target");
        for (int i = 0; i < targetList.size(); i++) {
            TargetEntity target = new TargetEntity();
            Element e = targetList.get(i);
            String tId = e.getAttributeValue("id");//targetId
            String name = e.getChildText("name");//target名称
            String comment = e.getChildText("comment");//target描述
            String hosts = e.getChildText("hosts");//目标主机地址
            String excludeHosts = e.getChildText("exclude_hosts");//排除主机地址
            //获取portlist id
            Element port = e.getChild("port_list");
            String portId = port.getAttributeValue("id");//端口列表ID
            //获取凭证
            Element ssh_credential = e.getChild("ssh_credential");
            Element smbCredential = e.getChild("smbCredential");
            Element esxiCredential = e.getChild("esxiCredential");
            Element snmpCredential = e.getChild("snmpCredential");
            String sshId = ssh_credential.getAttributeValue("id");
            //String smbId = smbCredential.getAttributeValue("id");
            //String esxiId = esxiCredential.getAttributeValue("id");
            //String snmpId = snmpCredential.getAttributeValue("id");

            String smbId = getAttributeValueCatch(smbCredential, "id");
            String esxiId = getAttributeValueCatch(esxiCredential, "id");
            String snmpId = getAttributeValueCatch(snmpCredential, "id");
            String reverseLookupOnly = e.getChildText("reverse_lookup_only");
            String reverseLookupUnify = e.getChildText("reverse_lookup_unify");
            String aliveTests = e.getChildText("alive_tests");
            target.setUuid(tId);
            target.setName(name);
            target.setComment(comment);
            target.setHosts(hosts);
            target.setExclude_hosts(excludeHosts);
            target.setPortId(portId);
            target.setSsh_lsc_credential(sshId);
            target.setSmb_lsc_credential(smbId);
            target.setEsxi_lsc_credential(esxiId);
            target.setReverse_lookup_only(reverseLookupOnly);
            target.setReverse_lookup_unify(reverseLookupUnify);
            target.setAlive_tests(aliveTests);

            resultList.add(target);
        }
        return resultList;
    }

    private String getAttributeValueCatch(Element el, String val) {
        // TODO Auto-generated method stub

        try {
            return el.getAttributeValue(val);

        } catch (Exception e) {
            // TODO: handle exception
            return null;
        }
    }

    @Override
    public TargetEntity getOneTarget(String targetId) throws Exception {
        //存储格式：[{name：name,comment:comment,credential:[{},{},{}]}，{}，{}，。。。]
        StringBuilder xmlcmd = new StringBuilder();
        TargetEntity result = new TargetEntity();
        xmlcmd.append("<get_targets target_id='" + targetId + "'/>");

        //String xmlString = exec( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        String xmlString = exec(command + xmlcmd + "'");
        //String xmlString = execSshCMD( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
        Element etarget = root.getChild("target");
        String tId = etarget.getAttributeValue("id");//targetId
        String name = etarget.getChildText("name");//target名称
        String comment = etarget.getChildText("comment");//target描述
        String hosts = etarget.getChildText("hosts");//目标主机地址
        String excludeHosts = etarget.getChildText("exclude_hosts");//排除主机地址
        //获取portlist id
        Element port = etarget.getChild("port_list");
        String portId = port.getAttributeValue("id");//端口列表ID
        //获取凭证
        Element ssh_credential = etarget.getChild("ssh_credential");
        Element smbCredential = etarget.getChild("smbCredential");
        Element esxiCredential = etarget.getChild("esxiCredential");
        Element snmpCredential = etarget.getChild("snmpCredential");
        String sshId = ssh_credential.getAttributeValue("id");
        String smbId = smbCredential.getAttributeValue("id");
        String esxiId = esxiCredential.getAttributeValue("id");
        String snmpId = snmpCredential.getAttributeValue("id");
        String reverseLookupOnly = etarget.getChildText("reverse_lookup_only");
        String reverseLookupUnify = etarget.getChildText("reverse_lookup_unify");
        String aliveTests = etarget.getChildText("alive_tests");

        result.setUuid(tId);
        result.setName(name);
        result.setComment(comment);
        result.setHosts(hosts);
        result.setExclude_hosts(excludeHosts);
        result.setPortId(portId);
        result.setSsh_lsc_credential(sshId);
        result.setSmb_lsc_credential(smbId);
        result.setEsxi_lsc_credential(esxiId);
        result.setReverse_lookup_only(reverseLookupOnly);
        result.setReverse_lookup_unify(reverseLookupUnify);
        result.setAlive_tests(aliveTests);
        return result;
    }

    @Override
    public void createTarget(TargetEntity target) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<create_target>");
        xmlcmd.append("<name>" + target.getName() + "</name>");
        xmlcmd.append("<hosts>" + target.getHosts() + "</hosts>");
        xmlcmd.append("<reverse_lookup_only>" + target.getReverse_lookup_only() + "</reverse_lookup_only>");
        xmlcmd.append("<reverse_lookup_unify>" + target.getReverse_lookup_unify() + "</reverse_lookup_unify>");
        xmlcmd.append("<port_list id=\"" + target.getPortId() + "\"/>");
        xmlcmd.append("<alive_tests>" + target.getAlive_tests() + "</alive_tests>");
        /*if (target.getExclude_hosts() != null && !target.getExclude_hosts().isEmpty()) {
            xmlcmd.append("<exclude_hosts>" + target.getExclude_hosts() + "</exclude_hosts>");
        }
        if (target.getComment() != null && !target.getComment().isEmpty()) {
            xmlcmd.append("<comment>" + target.getComment() + "</comment>");
        }
        if (target.getSsh_lsc_credential() != null && !target.getSsh_lsc_credential().isEmpty()) {
            xmlcmd.append("<ssh_lsc_credential id=\"" + target.getSsh_lsc_credential() + "\">");
            if (target.getSsh_port() != null && !target.getSsh_port().isEmpty()) {
                xmlcmd.append("<port>" + target.getSsh_port() + "</port>");
            }
            xmlcmd.append("</ssh_lsc_credential>");
        }
        if (target.getSmb_lsc_credential() != null && !target.getSmb_lsc_credential().isEmpty()) {
            xmlcmd.append("<smb_lsc_credential id=\"" + target.getSmb_lsc_credential() + "\"/>");
        }
        if (target.getEsxi_lsc_credential() != null && !target.getEsxi_lsc_credential().isEmpty()) {
            xmlcmd.append("<esxi_lsc_credential id=\"" + target.getEsxi_lsc_credential() + "\"/>");
        }*/
        xmlcmd.append("</create_target>");
        String xmlString = null;

        //xmlString = exec( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        xmlString = exec(command + xmlcmd + "'");
        //xmlString = execSshCMD( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
    }

    @Override
    public void deleteTarget(String targetId) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<delete_target target_id='" + targetId + "'/>");

        //String xmlString = exec( "omp -u admin -w admin --xml=\"" + xmlcmd + "\"");
        String xmlString = exec("gvm-cli --gmp-username admin --gmp-password contrail123  socket --sockpath /run/gvm/gvmd.sock --xml \"" + xmlcmd + "\"");
        //String xmlString = execSshCMD( "omp -u admin -w admin --xml=\"" + xmlcmd + "\"");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
    }

    @Override
    public void modifyTarget(TargetEntity target) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<modify_target target_id='" + target.getUuid() + "'>");
        xmlcmd.append("<name>" + target.getName() + "</name>");
        xmlcmd.append("<hosts>" + target.getHosts() + "</hosts>");
        xmlcmd.append("<reverse_lookup_only>" + target.getReverse_lookup_only() + "</reverse_lookup_only>");
        xmlcmd.append("<reverse_lookup_unify>" + target.getReverse_lookup_unify() + "</reverse_lookup_unify>");
        xmlcmd.append("<port_list id='" + target.getPortId() + "'/>");
        xmlcmd.append("<alive_tests>" + target.getAlive_tests() + "</alive_tests>");
        if (target.getExclude_hosts() != null && !target.getExclude_hosts().isEmpty()) {
            xmlcmd.append("<exclude_hosts>" + target.getExclude_hosts() + "</exclude_hosts>");
        }
        if (target.getComment() != null && !target.getComment().isEmpty()) {
            xmlcmd.append("<comment>" + target.getComment() + "</comment>");
        }
        if (target.getSsh_lsc_credential() != null && !target.getSsh_lsc_credential().isEmpty()) {
            xmlcmd.append("<ssh_lsc_credential id='" + target.getSsh_lsc_credential() + "'>");
            if (target.getSsh_port() != null && !target.getSsh_port().isEmpty()) {
                xmlcmd.append("<port>" + target.getSsh_port() + "</port>");
            }
            xmlcmd.append("</ssh_lsc_credential>");
        }
        if (target.getSmb_lsc_credential() != null && !target.getSmb_lsc_credential().isEmpty()) {
            xmlcmd.append("<smb_lsc_credential id='" + target.getSmb_lsc_credential() + "'/>");
        }
        if (target.getEsxi_lsc_credential() != null && !target.getEsxi_lsc_credential().isEmpty()) {
            xmlcmd.append("<esxi_lsc_credential id='" + target.getEsxi_lsc_credential() + "'/>");
        }
        xmlcmd.append("</modify_target>");

        //String xmlString = exec( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        String xmlString = exec(command + xmlcmd + "'");
        //String xmlString = execSshCMD( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
    }

    @Override
    public void createTask(TaskEntity task) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        task.setScannerId("08b69003-5fc2-4037-a479-93b440211c73");
        task.setConfigId("daba56c8-73ec-11df-a475-002264764cea");
        xmlcmd.append("<create_task>");
        xmlcmd.append("<name>" + task.getName() + "</name>");
        xmlcmd.append("<config id=\"" + task.getConfigId() + "\"/>");


        xmlcmd.append("<target id=\"" + task.getTargetId() + "\"/>");
        xmlcmd.append("<scanner id=\"" + task.getScannerId() + "\"/>");

        xmlcmd.append("</create_task>");
        String xmlString = null;
        String os = System.getProperty("os.name");
        //if(os.toLowerCase().startsWith("win")){

        //xmlString = exec( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        xmlString = exec(command + xmlcmd + "'");
        //xmlString = execSshCMD( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        //}else {
        //xmlString = exec( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        //}

        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
    }

    @Override
    public String startTask(String taskId) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<start_task task_id=\"" + taskId + "\"/>");
        String xmlString = null;
        String os = System.getProperty("os.name");

        //if(os.toLowerCase().startsWith("win")){
        //xmlString = exec( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        xmlString = exec(command + xmlcmd + "'");
        //xmlString = execSshCMD( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        //}else {
        // xmlString = exec( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        // }
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
        //返回报告Id
        String reportId = root.getChildText("report_id");
        return reportId;
    }

    @Override
    public String startWizardTask(String host) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<run_wizard>");
        xmlcmd.append("<name>快速扫描-" + host + "</name>");
        xmlcmd.append("<params>");
        xmlcmd.append("<param>");
        xmlcmd.append("<name>hosts</name>");
        xmlcmd.append("<value>" + host + "</value>");
        xmlcmd.append("</param>");
        xmlcmd.append("</params>");
        xmlcmd.append("</run_wizard>");

        //String xmlString = exec( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        String xmlString = exec(command + xmlcmd + "'");
        //String xmlString = execSshCMD( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
        Element startroot = root.getChild("response").getChild("start_task_response ");
        judgeStatus(startroot);
        //返回报告Id
        String reportId = startroot.getChildText("report_id");
        return reportId;
    }

    @Override
    public void stopTask(String taskId) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<stop_task task_id=\"" + taskId + "\"/>");

        //String xmlString = exec( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        String xmlString = exec(command + xmlcmd + "'");
        //String xmlString = execSshCMD( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
    }

    @Override
    public void modifyPortList(String portId, String name, String comment) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<modify_port_list port_list_id='" + portId + "'>");
        xmlcmd.append("<name>" + name + "</name>");
        xmlcmd.append("<comment>" + comment + "</comment>");
        xmlcmd.append("</modify_port_list>");

        //String xmlString = exec( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        String xmlString = exec(command + xmlcmd + "'");
        //String xmlString = execSshCMD( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
    }

    @Override
    public List<ConfigEntity> getConfigList() throws Exception {
        //存储格式：[{id:id,name:name},{},{}...]
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<get_configs/>");
        //String xmlString = exec( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        String xmlString = exec(command + xmlcmd + "'");
        //String xmlString = execSshCMD( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);

        Element root = doc.getRootElement();
        judgeStatus(root);
        List<Element> configlist = root.getChildren("config");
        List<ConfigEntity> resultList = new ArrayList<ConfigEntity>();
        for (int i = 0; i < configlist.size(); i++) {
            Element e = configlist.get(i);
            ConfigEntity config = new ConfigEntity();
            String configId = e.getAttributeValue("id");
            String name = e.getChildText("name");
            config.setId(configId);
            config.setName(name);
            resultList.add(config);
        }
        return resultList;
    }

    //獲取未完成的任務個數
    public int getTasksNum() throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<get_tasks filter=\"sort=name first=1 rows=9999\"/>");
        String xmlString = null;
        //xmlString = exec( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        xmlString = exec(command + xmlcmd + "'");
        //xmlString = execSshCMD( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
        List<Element> tasklist = root.getChildren("task");
        int tasksNum = 0 ;
        for (int i = 0; i < tasklist.size(); i++) {
            Element e = tasklist.get(i);

            String status = e.getChildText("status");
            switch (status) {
                case "Done":
                    status = "已完成";
                    break;
                case "Running":
                    status = e.getChildText("progress") + "%";
                    tasksNum++;
                    break;
                case "Stopped":
                    status = "终止";
                    tasksNum++;
                    break;
                default:
                    status = "等待中";
                    tasksNum++;
                    break;
            }

        }
        return tasksNum;
    }

    @Override
    public List<TaskInfoEntity> getTasksList() throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<get_tasks filter=\"sort=name first=1 rows=9999\"/>");
        String xmlString = null;

        //xmlString = exec( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        xmlString = exec(command + xmlcmd + "'");
        //xmlString = execSshCMD( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
        List<Element> tasklist = root.getChildren("task");
        List<TaskInfoEntity> resultList = new ArrayList<TaskInfoEntity>();
        for (int i = 0; i < tasklist.size(); i++) {
            Element e = tasklist.get(i);
            String tId = e.getAttributeValue("id");
            String name = e.getChildText("name");
            String checkTime = e.getChildText("modification_time");
            String configId = e.getChild("config").getAttributeValue("id");
            String targetId = e.getChild("target").getAttributeValue("id");
            Element report = e.getChild("last_report");
            String reportId = null;
            if (report != null) {
                reportId = report.getChild("report").getAttributeValue("id");
            }
            String status = e.getChildText("status");
            switch (status) {
                case "Done":
                    status = "已完成";
                    break;
                case "Running":
                    status = e.getChildText("progress") + "%";
                    break;
                case "Stopped":
                    status = "终止";
                    break;
                default:
                    status = "等待中";
                    break;
            }
            String severity = null;
            int resultcount = 0;

           /* Element reportInfo = e.getChild("first_report").getChild("report");
            Element resultInfo = reportInfo.getChild("result_count");
            severity = reportInfo.getChildText("severity");
            int debugCount = Integer.parseInt(resultInfo.getChildText("debug"));
            int holeCount = Integer.parseInt(resultInfo.getChildText("hole"));
            int infoCount = Integer.parseInt(resultInfo.getChildText("info"));
            int logCount = Integer.parseInt(resultInfo.getChildText("log"));
            int warningCount = Integer.parseInt(resultInfo.getChildText("warning"));
            int falsePositiveCount = Integer.parseInt(resultInfo.getChildText("false_positive"));
            resultcount = debugCount + holeCount + infoCount + logCount + warningCount + falsePositiveCount;*/

            TaskInfoEntity task = new TaskInfoEntity();
            task.setTaskId(tId);
            task.setName(name);
            task.setConfigId(configId);
            task.setTargetId(targetId);
            task.setReportId(reportId);
            task.setStatus(status);
            task.setSeverity(severity);
            task.setResultcount(resultcount);
            //转换时间
            SimpleDateFormat dff = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH);//输入的被转化的时间格式
            SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//需要转化成的时间格式
            Date checkDate = dff.parse(checkTime);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(checkDate);
            calendar.add(Calendar.HOUR_OF_DAY, 8);
            String ctime = df1.format(calendar.getTime());
            /*Date parse = sdf.parse(checkTime);
            Calendar rightNow = Calendar.getInstance();
            rightNow.setTime(parse);
            rightNow.add(Calendar.HOUR_OF_DAY, 16);
            String format = sdf.format(rightNow.getTime());
            task.setCheckTime(format);*/
            task.setCheckTime(ctime);
            resultList.add(task);
        }
        return resultList;
    }

    @Override
    public TaskInfoEntity getOneTask(String taskId) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<get_tasks task_id='" + taskId + "'/>");

        //String xmlString = exec( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        String xmlString = exec(command + xmlcmd + "'");
        //String xmlString = execSshCMD( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
        Element etask = root.getChild("task");
        TaskInfoEntity result = new TaskInfoEntity();
        String tId = etask.getAttributeValue("id");
        String name = etask.getChildText("name");
        String checkTime = etask.getChildText("modification_time");
        String configId = etask.getChild("config").getAttributeValue("id");
        String targetId = etask.getChild("target").getAttributeValue("id");
        String status = etask.getChildText("status");
        switch (status) {
            case "Done":
                status = "已完成";
                break;
            case "Running":
                status = etask.getChildText("progress") + "%";
                break;
            case "Stopped":
                status = "终止";
                break;
            default:
                status = "等待中";
                break;
        }
        Element reportInfo = etask.getChild("first_report").getChild("report");
        Element resultInfo = reportInfo.getChild("result_count");
        String severity = reportInfo.getChildText("severity");
        int debugCount = Integer.parseInt(resultInfo.getChildText("debug"));
        int holeCount = Integer.parseInt(resultInfo.getChildText("hole"));
        int infoCount = Integer.parseInt(resultInfo.getChildText("info"));
        int logCount = Integer.parseInt(resultInfo.getChildText("log"));
        int warningCount = Integer.parseInt(resultInfo.getChildText("warning"));
        int falsePositiveCount = Integer.parseInt(resultInfo.getChildText("false_positive"));
        int resultcount = debugCount + holeCount + infoCount + logCount + warningCount + falsePositiveCount;
        result.setTaskId(tId);
        result.setName(name);
        result.setConfigId(configId);
        result.setTargetId(targetId);
        result.setStatus(status);
        result.setSeverity(severity);
        result.setResultcount(resultcount);
        //转换时间
        SimpleDateFormat dff = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH);//输入的被转化的时间格式
        SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//需要转化成的时间格式
        Date checkDate = dff.parse(checkTime);
        String ctime = df1.format(checkDate);
        result.setCheckTime(ctime);
        return result;
    }

    @Override
    public void createUser(String userName) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<create_user>");
        xmlcmd.append("<name>" + userName + "</name>");
        xmlcmd.append("<password>123456</password>");
        xmlcmd.append("<role id=\"7a8cb5b4-b74d-11e2-8187-406186ea4fc5\"/>");
        xmlcmd.append("</create_user>");

        //String xmlString = exec( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        String xmlString = exec(command + xmlcmd + "'");
        //String xmlString = execSshCMD( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
    }

    @Override
    public void authenticateUser(UserEntity user) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<authenticate>");
        xmlcmd.append("<credentials>");
        xmlcmd.append("<username>" + user.getUsername() + "</username>");
        xmlcmd.append("<password>" + user.getPassword() + "</password>");
        xmlcmd.append("</credentials>");
        xmlcmd.append("</authenticate>");

        //String xmlString = exec( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        String xmlString = exec(command + xmlcmd + "'");
        //String xmlString = execSshCMD( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
    }

    @Override
    public void deleteUser(UserEntity user) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<delete_user name='" + user.getUsername() + "'/>");

        //String xmlString = exec( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        String xmlString = exec(command + xmlcmd + "'");
        //String xmlString = execSshCMD( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
    }

    @Override
    public void deleteTask(String taskId) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<delete_task task_id='" + taskId + "'/>");

        //String xmlString = exec("omp -u admin -w admin --xml=\"" + xmlcmd + "\"");
        String xmlString = exec("gvm-cli --gmp-username admin --gmp-password contrail123  socket --sockpath /opt/gvm/run/gvm/gvmd.sock --xml \"" + xmlcmd + "\"");
        //String xmlString = execSshCMD("omp -u admin -w admin --xml=\"" + xmlcmd + "\"");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
    }

    @Override
    public Map<String, Object> getReport(String reportId) throws Exception {
        //存储格式：{count:count,results:[{},{},{}....]}
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<get_reports report_id=\"" + reportId + "\"/>");

        //String xmlString = exec( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        String xmlString = exec(command + xmlcmd + "'");
        //String xmlString = execSshCMD( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
        Element reportInfo = root.getChild("report").getChild("report");
        //结果数目
        Element resultCountInfo = reportInfo.getChild("result_count");
        //int debugCount = Integer.parseInt(resultCountInfo.getChild("debug").getChildText("full"));
        int holeCount = Integer.parseInt(resultCountInfo.getChild("hole").getChildText("full"));
        int infoCount = Integer.parseInt(resultCountInfo.getChild("info").getChildText("full"));
        int logCount = Integer.parseInt(resultCountInfo.getChild("log").getChildText("full"));
        int warningCount = Integer.parseInt(resultCountInfo.getChild("warning").getChildText("full"));
        int falsePositiveCount = Integer.parseInt(resultCountInfo.getChild("false_positive").getChildText("full"));
        Map<String, Object> resultmap = new HashMap<String, Object>();
        resultmap.put("debugCount", 0);
        resultmap.put("holeCount", holeCount);
        resultmap.put("infoCount", infoCount);
        resultmap.put("logCount", logCount);
        resultmap.put("warningCount", warningCount);
        resultmap.put("falsePositiveCount", falsePositiveCount);
        if (holeCount==0 && infoCount==0 && logCount ==0 && warningCount==0){
            //throw  new ServiceException(dwEnum.FAILURE.code(), "当前扫描任务无报告");
        }
        List<Map<String, Object>> resultInfoList = new ArrayList<Map<String, Object>>();
        //result结果信息

        StringBuilder resultCmd = new StringBuilder();
        resultCmd.append("<get_results report_id=\"" + reportId + "\"  filter=\"first=1 rows=9999\"/>");
        //resultCmd.append("<get_results report_id=\"" + reportId + "\"/>");
        String resultString = exec(command + resultCmd + "'");
        Document resultDoc = getDocument(resultString);
        Element resultRoot = resultDoc.getRootElement();
        judgeStatus(resultRoot);
        List<Element> results = resultRoot.getChildren("result");
        for (int i = 0; i < results.size(); i++) {
            Element e = results.get(i);
            Map<String, Object> eresultmap = new HashMap<String, Object>();
            String resultId = e.getAttributeValue("id");
            String name = e.getChildText("name");
            String host = e.getChildText("host");
            String hostname = e.getChild("host").getChildText("hostname");
            String port = e.getChildText("port");
            String severity = e.getChildText("severity");
            String threat = e.getChildText("threat");
            switch (threat) {
                case "Medium":
                    threat = "中";
                    break;
                case "High":
                    threat = "高";
                    break;
                case "Low":
                    threat = "低";
                case "Log":
                    break;
                default:
                    break;
            }
            String qod = e.getChild("qod").getChildText("value");
            eresultmap.put("resultId", resultId);
            eresultmap.put("name", name);
            eresultmap.put("host", host);
            eresultmap.put("hostname",hostname);
            eresultmap.put("port", port);
            eresultmap.put("severity", severity);
            eresultmap.put("threat", threat);
            eresultmap.put("qod", qod);

            resultInfoList.add(eresultmap);
        }
        resultmap.put("results", resultInfoList);
        return resultmap;
    }

    @Override
    public Map<String, Object> getReportResult(String resultId) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<get_results result_id=\"" + resultId + "\"/>");
        //String xmlString = exec( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        String xmlString = exec(command + xmlcmd + "'");
        //String xmlString = execSshCMD( "omp -u admin -w admin --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Element resultInfo = root.getChild("result");
        String name = resultInfo.getChildText("name");
        String qod = resultInfo.getChild("qod").getChildText("value");
        String host = resultInfo.getChildText("host");
        String hostname = resultInfo.getChild("host").getChildText("hostname");
        String port = resultInfo.getChildText("port");

        resultMap.put("name", name);//名称
        resultMap.put("qod", qod);//评分
        resultMap.put("host", host);//目标主机
        resultMap.put("hostname",hostname);
        resultMap.put("port", port);//端口
        Element nvtInfo = resultInfo.getChild("nvt");
       /* try {
            Element refs = nvtInfo.getChild("refs");
            List<Element> children = refs.getChildren();
            cve = nvtInfo.getChild("refs").getChildren().get(0).getChildText("id");90-=
        }catch (Exception e){
            e.printStackTrace();
        }*/
        StringBuilder cve = new StringBuilder();
        Element refsEle = nvtInfo.getChild("refs");
        List<Element> refs = new ArrayList<>();
        if (refsEle != null) {
            refs = refsEle.getChildren();
        }
        for (Element ref : refs) {
            if (ref.getAttributeValue("type").equals("cve")) {
                String cve1 = ref.getAttributeValue("id");
                if (cve1 != null) {
                    cve.append(cve1 + "   ");
                }
            }
        }
        String cvss = nvtInfo.getChildText("cvss_base");//cvss 评分
        //String xref = nvtInfo.getChildText("xref");//Other:Xref
        //String[] xrefs = xref.split(",");
        //Element certInfo = nvtInfo.getChild("cert");
        //List<Element> certList = certInfo.getChildren("cert_ref");
       /* String certs = "";
        for (int i = 0; i < certList.size(); i++) {
            String id = certList.get(i).getAttributeValue("id");
            certs += id + ",";
        }

        certs = certs.substring(0, certs.length() - 1);*/
        String scanNvtVersion = resultInfo.getChildText("scan_nvt_version");
        resultMap.put("cvss", cvss);
        resultMap.put("cve", cve.toString());
        //resultMap.put("xrefs", xrefs);
        //resultMap.put("certs", certs);
        resultMap.put("scanNvtVersion", scanNvtVersion);

        String tags = nvtInfo.getChildText("tags");
        String[] tagsArray = tags.split("\\|");
        for (int i = 0; i < tagsArray.length; i++) {
            String estr = tagsArray[i];
            if (estr.contains("summary=")) {
                String summaryStr = estr.substring(estr.lastIndexOf("=") + 1, estr.length());// 摘要
                resultMap.put("summary", summaryStr);
            } else if (estr.contains("impact=")) {
                String impactStr = estr.substring(estr.lastIndexOf("=") + 1, estr.length());// 影响
                resultMap.put("impact", impactStr);
            } else if (estr.contains("solution=")) {
                String solutionStr = estr.substring(estr.lastIndexOf("=") + 1, estr.length());// 解决方法
                resultMap.put("solution", solutionStr);
            } else if (estr.contains("solution_type=")) {
                String solutionTypeStr = estr.substring(estr.lastIndexOf("=") + 1, estr.length());// 解决类型
                resultMap.put("solutionType", solutionTypeStr);
            } else if (estr.contains("affected=")) {
                String affectedStr = estr.substring(estr.lastIndexOf("=") + 1, estr.length());// 受影响的系统
                resultMap.put("affected", affectedStr);
            }
        }
        return resultMap;
    }
    @Override
    public void createCredentials(CredentialsEntity credentials) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<create_lsc_credential>");
        xmlcmd.append("<name>" + credentials.getName() + "</name>");
        xmlcmd.append("<login>" + credentials.getLogin() + "</login>");
        xmlcmd.append("<password>" + credentials.getPassword() + "</password>");
        xmlcmd.append("<comment>" + credentials.getComment() + "</comment>");
        xmlcmd.append("</create_lsc_credential>");

        //String xmlString = exec("omps -u admin -w admin --xml='" + xmlcmd + "'");
        String xmlString = exec(command + xmlcmd + "'");
        //String xmlString = execSshCMD("omps -u admin -w admin --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);

    }

    @Override
    public List<CredentialsEntity> getCredentialsList() throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<get_credentials/>");

        //String xmlString = exec("omps -u admin -w admin --xml='" + xmlcmd + "'");
        String xmlString = exec(command + xmlcmd + "'");
        //String xmlString = execSshCMD("omps -u admin -w admin --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
        List<CredentialsEntity> resultList = new ArrayList<CredentialsEntity>();
        List<Element> credentialList = root.getChildren("credential");
        for (int i = 0; i < credentialList.size(); i++) {
            CredentialsEntity credential = new CredentialsEntity();
            Element e = credentialList.get(i);
            String credentialId = e.getAttributeValue("id");
            String name = e.getChildText("name");
            String fullType = e.getChildText("full_type");
            String login = e.getChildText("login");
            int allowInsecure = Integer.parseInt(e.getChildText("allow_insecure"));
            String comment = e.getChildText("comment");

            credential.setUuid(credentialId);
            credential.setName(name);
            credential.setFullType(fullType);
            credential.setLogin(login);
            credential.setAllow_insecure(allowInsecure);
            credential.setComment(comment);

            resultList.add(credential);
        }
        return resultList;
    }

    @Override
    public CredentialsEntity getOneCredential(String cId) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<get_credentials credential_id='" + cId + "'/>");

        //String xmlString = exec("omps -u admin -w admin --xml='" + xmlcmd + "'");
        String xmlString = exec(command + xmlcmd + "'");
        //String xmlString = execSshCMD("omps -u admin -w admin --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
        CredentialsEntity result = new CredentialsEntity();
        Element ecredential = root.getChild("credential");
        String credentialId = ecredential.getAttributeValue("id");
        String name = ecredential.getChildText("name");
        String fullType = ecredential.getChildText("full_type");
        String login = ecredential.getChildText("login");
        int allowInsecure = Integer.parseInt(ecredential.getChildText("allow_insecure"));
        String comment = ecredential.getChildText("comment");

        result.setUuid(credentialId);
        result.setName(name);
        result.setFullType(fullType);
        result.setLogin(login);
        result.setAllow_insecure(allowInsecure);
        result.setComment(comment);

        return result;
    }

    @Override
    public void modifyCredentials(CredentialsEntity credentials) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<modify_credential credential_id='" + credentials.getUuid() + "'>");
        xmlcmd.append("<comment>" + credentials.getComment() + "</comment>");
        xmlcmd.append("<name>" + credentials.getName() + "</name>");
        xmlcmd.append("<password>" + credentials.getPassword() + "</password>");
        xmlcmd.append("<login>" + credentials.getLogin() + "</login>");
        xmlcmd.append("</modify_credential>");


        //String xmlString = exec("omps -u admin -w admin --xml='" + xmlcmd + "'");
        String xmlString = exec(command + xmlcmd + "'");
        //String xmlString = execSshCMD("omps -u admin -w admin --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
    }

    @Override
    public void deleteCredentials(CredentialsEntity credentials) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<delete_credential credential_id='" + credentials.getUuid() + "'/>");


        //String xmlString = exec("omps -u admin -w admin --xml='" + xmlcmd + "'");
        String xmlString = exec(command + xmlcmd + "'");
        //String xmlString = execSshCMD("omps -u admin -w admin --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
    }

    public static int exeCommand(String command, OutputStream out) throws ExecuteException, IOException {
        // 设置超时时间为10秒
        return exeCommand(command, out, 10000L);
    }

    public static int exeCommand(String command, OutputStream out, Long outTime) throws ExecuteException, IOException {
        CommandLine commandLine = CommandLine.parse(command);
        PumpStreamHandler pumpStreamHandler = null;
        if (null == out) {
            pumpStreamHandler = new PumpStreamHandler();
        } else {
            pumpStreamHandler = new PumpStreamHandler(out);
        } // 设置超时时间为outTime秒
        ExecuteWatchdog watchdog = new ExecuteWatchdog(outTime);
        DefaultExecutor executor = new DefaultExecutor();
        executor.setStreamHandler(pumpStreamHandler);
        executor.setWatchdog(watchdog);
        return executor.execute(commandLine);
    }

    public static void exUser() {
        String[] cmdA = {"/bin/sh", "-c", "su - gvm"};
        try {
            Process process = Runtime.getRuntime().exec(cmdA);
            DataOutputStream os = new DataOutputStream(process.getOutputStream());
            os.writeBytes("" + "\n");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
